﻿using System;
using System.Data;
using System.Collections.Generic;
using Maticsoft.Common;
using Travel.Model;
using EAD.Framework;
using System.Text;
using System.Configuration;
using System.Web;

namespace Travel.BLL
{
    /// <summary>
    /// users
    /// </summary>
    public partial class users
    {
        /// <summary>
        /// 用户名是否已经存在
        /// </summary>
        public bool IsExistsUserName(string userName)
        {
            using (IDBHandlerble db = DBHandlerFactory.CreateDBHander())
            {
                string num = db.ExecuteScalar("select count(Id) from users where user_name = '" + userName + "'", true).ToString();
                return Convert.ToInt32(num) > 0;
            }
        }

        /// <summary>
        ///  Email是否已经存在
        /// </summary>
        /// <param name="email">电子邮箱</param>
        /// <returns></returns>
        public bool IsExistsEmail(string email)
        {
            using (IDBHandlerble db = DBHandlerFactory.CreateDBHander())
            {
                string num = db.ExecuteScalar("select count(Id) from users where email = '" + email + "'", true).ToString();
                return Convert.ToInt32(num) > 0;
            }
        }

        /// <summary>
        ///  Email是否已经存在
        /// </summary>
        /// <param name="email">电子邮箱</param>
        /// <param name="userName">用户名</param>
        /// <returns></returns>
        public bool IsExistsEmail(string email, string userName)
        {
            using (IDBHandlerble db = DBHandlerFactory.CreateDBHander())
            {
                string num = db.ExecuteScalar("select count(Id) from users where email = '" + email + "' and user_name = '" + userName + "'", true).ToString();
                return Convert.ToInt32(num) > 1;
            }
        }


        #region 用户注册

        /// <summary>
        /// 用户注册
        /// </summary>
        /// <param name="userObj">用户实体类</param>
        /// <returns></returns>
        public bool Register(Model.users userObj)
        {
            var sql = new StringBuilder(52);
            sql.Append("insert into users(user_name,pwd,name,type,qq,email,");
            sql.Append("phone,created_on,created_by,changed_on,changed_by) ");
            sql.Append("values('" + userObj.user_name + "',");
            sql.Append("'" + userObj.pwd + "',");
            sql.Append("'',");
            sql.Append("1,");
            sql.Append("'',");
            sql.Append("'" + userObj.email + "',");
            sql.Append("'',");
            sql.Append("getdate(),");
            sql.Append("'',");
            sql.Append("getdate(),");
            sql.Append("'')");

            using (IDBHandlerble db = DBHandlerFactory.CreateDBHander())
            {
                return db.ExecuteNonQuery(sql.ToString(), true) > 0;
            }
        }

        #endregion

        #region 属性

        /// <summary>
        /// Cookie名称
        /// </summary>
        public string cookieName { get; set; }

        /// <summary>
        /// Cookie域名范围
        /// </summary>
        public string cookieDomain { get; set; }

        /// <summary>
        /// Cookie失效时间
        /// </summary>
        public string cookieTimeOut { get; set; }

        /// <summary>
        /// Cookie加密密钥
        /// </summary>
        public string cookieKey { get; set; }

        /// <summary>
        /// 当前用户登录实体类
        /// </summary>
        public Travel.Model.users UserDto { get; set; }

        #endregion

        #region 登录模块

        /// <summary>
        /// 用户登录
        /// </summary>
        /// <param name="userName">用户名</param>
        /// <param name="password">密码</param>
        /// <returns></returns>
        public bool Login(string userName, string password)
        {
            cookieName = ConfigurationSettings.AppSettings["cookie.name"];
            cookieDomain = ConfigurationSettings.AppSettings["cookie.domain"];
            cookieTimeOut = ConfigurationSettings.AppSettings["cookie.TimeOut"];
            cookieKey = ConfigurationSettings.AppSettings["cookie.Key"];

            using (IDBHandlerble db = DBHandlerFactory.CreateDBHander())
            {
                string sql = "select id,user_name,pwd,email from users where user_name = '" + userName + "' and pwd = '" + password + "'";
                DataTable userDt = db.ExecuteDataTable(sql);
                if (userDt != null && userDt.Rows.Count > 0)
                {
                    UserDto = SetUserDTO(userDt);
                    //1.写入Session
                    SetSession();
                    //2.写入Cookie
                    SetCookie();
                    //3.记录登录信息
                    //db.ExecuteNonQuery("update AA_Customer set LastLoginTime = getdate() where UserName = '" + userName + "'", true);
                    return true;
                }
            }
            return false;
        }

        /// <summary>
        /// 用户登录
        /// </summary>
        /// <param name="userName">用户名</param>
        /// <param name="password">密码</param>
        /// <param name="autoLogin">一个月内自动登录</param>
        /// <returns></returns>
        public bool Login(string userName, string password, string autoLogin)
        {
            cookieName = ConfigurationSettings.AppSettings["cookie.name"];
            cookieDomain = ConfigurationSettings.AppSettings["cookie.domain"];
            cookieTimeOut = ConfigurationSettings.AppSettings["cookie.TimeOut"];
            cookieKey = ConfigurationSettings.AppSettings["cookie.Key"];

            using (IDBHandlerble db = DBHandlerFactory.CreateDBHander())
            {
                string sql = "select id,user_name,pwd,email from users where user_name = '" + userName + "' and pwd = '" + password + "'";
                DataTable userDt = db.ExecuteDataTable(sql);
                if (userDt != null && userDt.Rows.Count > 0)
                {
                    UserDto = SetUserDTO(userDt);
                    //1.写入Session
                    SetSession();
                    //2.写入Cookie
                    if (autoLogin == "1")
                    {
                        SetCookie(30);
                    }
                    else
                    {
                        SetCookie();
                    }
                    return true;
                }
            }
            return false;
        }

        /// <summary>
        /// 是否登录
        /// </summary>
        /// <returns></returns>
        public bool IsLogin()
        {
            UserDto = GetCurrentUser();
            return UserDto != null;
        }

        /// <summary>
        /// 将当前用户写入Session变量
        /// </summary>
        public void SetSession()
        {
            if (UserDto != null)
            {
                SessionState.Set(cookieName, UserDto);
            }
        }

        /// <summary>
        /// 将当前用户写入Cookie变量(一个月)
        /// </summary>
        /// <param name="timeOut">Cookie有效期</param>
        public void SetCookie(int timeOut)
        {
            var context = HttpContext.Current;
            if (UserDto != null)
            {
                //cookie是否存在
                HttpCookie co = context.Request.Cookies.Get(cookieName);
                if (co == null)
                {
                    co = new HttpCookie(cookieName);
                }
                //将当前登录用户信息序列化后写入cookie
                co.Value = EncryptUserStr(UserDto);
                co.Expires = DateTime.Now.AddDays(timeOut);
                co.Domain = cookieDomain;
                context.Response.Cookies.Add(co);
            }
        }

        /// <summary>
        /// 将当前用户写入Cookie变量
        /// </summary>
        /// <param name="varName">变量名称</param>
        public void SetCookie()
        {
            var context = HttpContext.Current;
            if (UserDto != null)
            {
                //cookie是否存在
                HttpCookie co = context.Request.Cookies.Get(cookieName);
                if (co == null)
                {
                    co = new HttpCookie(cookieName);
                }
                //将当前登录用户信息序列化后写入cookie
                co.Value = EncryptUserStr(UserDto);
                co.Expires = DateTime.Now.AddMinutes(double.Parse(cookieTimeOut));
                co.Domain = cookieDomain;
                context.Response.Cookies.Add(co);
            }
        }

        #endregion

        #region 获取用户信息

        /// <summary>
        /// 获取当前登录用户信息
        /// </summary>
        /// <returns></returns>
        public Model.users GetCurrentUser()
        {
            CookieToSession(cookieName);
            if (SessionState.Get(cookieName) != null)
            {
                return SessionState.Get(cookieName) as Model.users;
            }
            return null;
        }

        /// <summary>
        /// 将读取到的COOKIE用户值存入Session
        /// </summary>
        /// <returns></returns>
        public string CookieToSession(string varName)
        {
            var context = HttpContext.Current;
            var co = context.Request.Cookies[varName];
            if (co != null)
            {
                UserDto = SetUserDTO(UncryptUserStr(co.Value));
                //将当前登录用户信息序列化后写入cookie
                co.Value = EncryptUserStr(UserDto);
                co.Expires = DateTime.Now.AddMinutes(double.Parse(cookieTimeOut));
                co.Domain = cookieDomain;
                context.Response.Cookies.Add(co);
                SessionState.Set(cookieName, UserDto);
            }
            return string.Empty;
        }

        /// <summary>
        /// 解密用户信息存入用户实体类
        /// </summary>
        /// <param name="cookieStr"></param>
        /// <returns></returns>
        public string UncryptUserStr(string cookieStr)
        {
            Security se = new Security();
            return se.Uncrypt(cookieStr, cookieKey);
        }

        /// <summary>
        /// 加密用户信息数据存入Cookie
        /// </summary>
        /// <param name="userDto"></param>
        /// <returns></returns>
        public string EncryptUserStr(Model.users userDto)
        {
            StringBuilder ss = new StringBuilder(52);
            ss.Append(UserDto.id + "|");
            ss.Append(UserDto.user_name + "|");
            ss.Append(UserDto.email + "|");

            Security se = new Security();
            return se.Encrypt(ss.ToString(), cookieKey);
        }

        /// <summary>
        /// 将值赋到实体类
        /// </summary>
        /// <param name="dt">用户DataTable信息</param>
        /// <returns></returns>
        public Model.users SetUserDTO(DataTable dt)
        {
            Model.users u = new Model.users();
            u.id = Convert.ToInt32(dt.Rows[0]["id"]);
            u.user_name = dt.Rows[0]["user_name"].ToString();
            u.email = dt.Rows[0]["email"].ToString();
            return u;
        }

        /// <summary>
        /// 将值赋到实体类
        /// </summary>
        /// <param name="userStr">用户cookie字符串</param>
        /// <returns></returns>
        public Model.users SetUserDTO(string userStr)
        {
            Model.users u = new Model.users();
            u.id = Convert.ToInt32(userStr.Split('|')[0]);
            u.user_name = userStr.Split('|')[1];
            u.email = userStr.Split('|')[2];
            return u;
        }

        #endregion

        #region 修改,找回

        /// <summary>
        /// 检测原始密码和用户名是否匹配
        /// </summary>
        /// <param name="userName">用户名</param>
        /// <param name="oldPwd">原始密码</param>
        /// <returns></returns>
        public static bool IsOldPwdTrue(string userName, string oldPwd)
        {
            string sql = "select count(Id) from AA_Customer where UserName = '" + userName + "' and Password = '" + oldPwd + "'";
            //return SqlTools.FindIntScalar(sql, "AA_Customer") > 0;
            return false;
        }

        /// <summary>
        /// 修改密码
        /// </summary>
        /// <param name="userName">用户名</param>
        /// <param name="oldPwd">旧密码</param>
        /// <param name="newPwd">新密码</param>
        /// <param name="exMsg">异常信息</param>
        public static bool EditPassword(string userName, string oldPwd, string newPwd, ref string exMsg)
        {
            exMsg = "密码修改成功!";
            if (!IsOldPwdTrue(userName, oldPwd))
            {
                exMsg = "原始密码不匹配!";
                return false;
            }

            string sql = "update AA_Customer set Password = '" + newPwd + "'";
            sql += " where userName = '" + userName + "' and Password = '" + oldPwd + "'";
            //return SqlTools.ExecuteNonQuery(sql, "AA_Customer") > 0;
            return false;
        }

        /// <summary>
        /// 修改个人信息
        /// </summary>
        /// <param name="uObj">用户实体类对象</param>
        /// <returns></returns>
        public static bool EditUserInfo(Model.users uObj)
        {
            StringBuilder sql = new StringBuilder(52);
            //sql.Append("update AA_Customer set ");
            //sql.Append("CustomerName = '" + uObj.CustomerName + "',");
            //sql.Append("Sex = '" + uObj.Sex + "',");
            //sql.Append("Birthday = '" + uObj.Birthday + "',");
            //sql.Append("Contact = '" + uObj.Contact + "',");
            //sql.Append("Mobile = '" + uObj.Mobile + "',");
            //sql.Append("Email = '" + uObj.Email + "',");
            //sql.Append("Fax = '" + uObj.Fax + "',");
            //sql.Append("Icon = '" + uObj.Icon + "',");
            //sql.Append("QQ = '" + uObj.QQ + "'");
            //sql.Append(" where userName = '" + uObj.UserName + "'");
            //return SqlTools.ExecuteNonQuery(sql.ToString(), "AA_Customer") > 0;
            return false;
        }

        /// <summary>
        /// 找回密码
        /// </summary>
        /// <param name="mobile">验证过的手机号码</param>
        /// <param name="newPwd">新密码</param>
        /// <param name="exMsg">异常信息</param>
        /// <returns></returns>
        public static bool ForgetPassword(string mobile, string newPwd, ref string exMsg)
        {
            exMsg = "密码找回成功!";

            StringBuilder sql = new StringBuilder(52);
            sql.Append("update users set Password = '" + newPwd + "'");
            sql.Append(" where email='" + mobile + "'");
            //if (SqlTools.ExecuteNonQuery(sql.ToString(), "AA_Customer") <= 0)
            //{
            //    exMsg = "密码找回失败,请联系客服!";
            //    return false;
            //}
            return true;
        }

        #endregion

    }
}

